<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <link href="/static/img/logo/logo.png" rel="icon">
    <title>Serverless Platform</title>
    <link href="/static/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="/static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="/static/css/ruang-admin.min.css" rel="stylesheet">
    <script src="/static/code/highcharts.src.js"></script>
    <script src="/static/code/modules/exporting.js"></script>
    <script src="/static/code/modules/export-data.js"></script>
    <script src="/static/code/modules/accessibility.js"></script>
    <style type="text/css">
    </style>
</head>

<body>
<div id="content">

    <!-- Container Fluid-->
    <div class="container-fluid" id="container-wrapper">
        <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">Dashboard</h1>
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="./">Home</a></li>
                <li class="breadcrumb-item active" aria-current="page">Dashboard</li>
            </ol>
        </div>

        <div class="row mb-3">
            <!-- Earnings (Monthly) Card Example -->
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold  mb-1">K8S Cluster : MASTER</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">Pods : <a href="#">12</a></div>
                                <div class="mt-2 mb-0 text-muted text-xs">
                                    <span class="text-success mr-2"><img src="/static/images/running.png" style="width: 20px;height: 20px;margin-right: 5px">running</span>
                                    <span>since 2 months ago</span>
                                </div>
                            </div>
                            <div class="col-auto">
                                <img src="/static/images/s4.png" style="width: 64px;height: 64px">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Earnings (Annual) Card Example -->
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold  mb-1">K8S Cluster : NODE01</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">Pods : <a href="#">15</a></div>
                                <div class="mt-2 mb-0 text-muted text-xs">
                                    <span class="text-success mr-2"><img src="/static/images/running.png" style="width: 20px;height: 20px;margin-right: 5px">running</span>
                                    <span>since 2 months ago</span>
                                </div>
                            </div>
                            <div class="col-auto">
                                <img src="/static/images/s2.png" style="width: 64px;height: 64px">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- New User Card Example -->
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold  mb-1">K8S Cluster : NODE02</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">Pods : <a href="#">13</a></div>
                                <div class="mt-2 mb-0 text-muted text-xs">
                                    <span class="text-success mr-2"><img src="/static/images/running.png" style="width: 20px;height: 20px;margin-right: 5px">running</span>
                                    <span>since 2 months ago</span>
                                </div>
                            </div>
                            <div class="col-auto">
                                <img src="/static/images/s3.png" style="width: 64px;height: 64px">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Pending Requests Card Example -->
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold  mb-1">K8S Cluster : NFS SERVER</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">Mount Devices: <a href="#">3</a></div>
                                <div class="mt-2 mb-0 text-muted text-xs">
                                    <span class="text-success mr-2"><img src="/static/images/running.png" style="width: 20px;height: 20px;margin-right: 5px">running</span>
                                    <span>since 2 months ago</span>
                                </div>
                            </div>
                            <div class="col-auto">
                                <img src="/static/images/d1.png" style="width: 64px;height: 64px">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Deployed Function InvocationCount -->
            <div class="col-xl-6 col-lg-7">
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Deployed Function InvocationCount</h6>
                    </div>
                    <div class="card-body">
                        <div class="chart-bar">
                            <canvas id="myBarChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <!-- live table -->
            <div class="col-xl-6 col-lg-5">
                <div class="card mb-4">
                    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                        <h6 class="m-0 font-weight-bold text-primary">Function Instances</h6>
                        <div class="dropdown no-arrow">
                            Function Name :
                            <a class="dropdown-toggle btn btn-primary btn-sm" href="#" role="button"
                               id="dropdownMenuLink"
                               data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                               {{ selected_function_name }} <i class="fas fa-chevron-down"></i>
                            </a>
                            <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in"
                                 aria-labelledby="dropdownMenuLink">
                                <div class="dropdown-header">Select Periode</div>
                                {% for function_name in functions_name %}
                                    {% if function_name == selected_function_name %}
                                        <a class="dropdown-item active" href="/function/get_dashboard_for_special_function_page?username={{ username }}&selected_function_name={{ function_name }}">{{ function_name }}</a>
                                    {% else %}
                                        <a class="dropdown-item" href="/function/get_dashboard_for_special_function_page?username={{ username }}&selected_function_name={{ function_name }}">{{ function_name }}</a>
                                    {% endif %}
                                {% endfor %}

{#                                <a class="dropdown-item active" href="#">Month</a>#}
                            </div>
                        </div>
                    </div>
                    <div id="container"></div>
                </div>
            </div>

        </div>
    </div>
    <!---Container Fluid-->
</div>


<script src="/static/vendor/jquery/jquery.min.js"></script>
<script src="/static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/static/vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="/static/js/ruang-admin.min.js"></script>
<script src="/static/vendor/chart.js/Chart.min.js"></script>
<script src="/static/js/demo/chart-area-demo.js"></script>

<script>
    Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
    Chart.defaults.global.defaultFontColor = '#858796';

    function number_format(number, decimals, dec_point, thousands_sep) {
        // *     example: number_format(1234.56, 2, ',', ' ');
        // *     return: '1 234,56'
        number = (number + '').replace(',', '').replace(' ', '');
        var n = !isFinite(+number) ? 0 : +number,
            prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
            sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
            dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
            s = '',
            toFixedFix = function (n, prec) {
                var k = Math.pow(10, prec);
                return '' + Math.round(n * k) / k;
            };
        // Fix for IE parseFloat(0.55).toFixed(0) = 0;
        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        if (s[0].length > 3) {
            s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
        }
        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0');
        }
        return s.join(dec);
    }

    let functions_name, functions_invocation, myBarChart,instance_for_special_function;
    $(function () {
        $.get('/function/get_deployed_function_info?username={{ username }}',function (res) {
            functions_name = res['functions_name']
            functions_invocation = res['functions_invocation']
            let max_function_invocation = res['max_function_invocation']
            instance_for_special_function = res['instance_for_special_function']
            const ctx = document.getElementById("myBarChart");
            myBarChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: functions_name,
                    datasets: [{
                        label: "InvocationCount",
                        backgroundColor: "#4e73df",
                        hoverBackgroundColor: "#2e59d9",
                        borderColor: "#4e73df",
                        data: functions_invocation,
                    }],
                },
                options: {
                    maintainAspectRatio: false,
                    layout: {
                        padding: {
                            left: 10,
                            right: 25,
                            top: 25,
                            bottom: 0
                        }
                    },
                    scales: {
                        xAxes: [{
                            scaleLabel: {
                                labelString: 'Function Name',
                                display: true,
                            },
                            time: {
                                unit: 'month'
                            },
                            gridLines: {
                                display: false,
                                drawBorder: false
                            },
                            ticks: {
                                maxTicksLimit: 6,
                            },
                            maxBarThickness: 25,
                        }],
                        yAxes: [{
                            scaleLabel: {
                                labelString: 'Function InvocationCount',
                                display: true,
                            },
                            ticks: {
                                min: 0,
                                max: max_function_invocation * 1.35,
                                maxTicksLimit: 20,
                                padding: 2,
                                // Include a dollar sign in the ticks
                                callback: function (value, index, values) {
                                    return number_format(value);
                                }
                            },
                            gridLines: {
                                color: "rgb(234, 236, 244)",
                                zeroLineColor: "rgb(234, 236, 244)",
                                drawBorder: true,
                                borderDash: [2],
                                zeroLineBorderDash: [2]
                            }
                        }],
                    },
                    legend: {
                        display: true
                    },
                    tooltips: {
                        titleMarginBottom: 10,
                        titleFontColor: '#6e707e',
                        titleFontSize: 14,
                        backgroundColor: "rgb(255,255,255)",
                        bodyFontColor: "#858796",
                        borderColor: '#dddfeb',
                        borderWidth: 1,
                        xPadding: 15,
                        yPadding: 15,
                        displayColors: false,
                        caretPadding: 10,
                        callbacks: {
                            label: function (tooltipItem, chart) {
                                const datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || '';
                                return datasetLabel + ': ' + number_format(tooltipItem.yLabel);
                            }
                        }
                    },
                }
            });

        })

        setInterval(update_data, 1000)

        // live table
        Highcharts.chart('container', {
            chart: {
                type: 'spline',
                animation: Highcharts.svg, // don't animate in old IE
                marginRight: 10,
                events: {
                    load: function () {
                        // set up the updating of the chart each second
                        const series = this.series[0];
                        setInterval(function () {
                            const x = (new Date()).getTime(), // current time
                                y = instance_for_special_function['{{ selected_function_name }}'];
                            series.addPoint([x, y], true, true);
                        }, 1000);
                    }
                }
            },

            time: {
                useUTC: false
            },

            title: {
                text: ''
            },

            accessibility: {
                announceNewData: {
                    enabled: true,
                    minAnnounceInterval: 15000,
                    announcementFormatter: function (allSeries, newSeries, newPoint) {
                        if (newPoint) {
                            return 'New point added. Value: ' + newPoint.y;
                        }
                        return false;
                    }
                }
            },

            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150
            },

            yAxis: {
                title: {
                    text: 'Function Instances'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },

            tooltip: {
                headerFormat: '<b>{series.name}</b><br/>',
                pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f}'
            },

            legend: {
                enabled: false
            },

            exporting: {
                enabled: false
            },

            series: [{
                name: 'Function Instances',
                data: (function () {
                    // generate an array of random data
                    var data = [],
                        time = (new Date()).getTime(),
                        i;

                    for (i = -19; i <= 0; i += 1) {
                        data.push({
                            x: time + i * 1000,
                            y: {{ selected_function_instances }}
                        });
                    }
                    return data;
                }())
            }]
        });
    })

    function update_data() {
        $.get('/function/get_deployed_function_info?username={{ username }}', function (res) {
            functions_name = res['functions_name']
            functions_invocation = res['functions_invocation']
            let max_function_invocation = res['max_function_invocation']

            if (max_function_invocation > 0.8 * myBarChart.options.scales.yAxes[0].ticks.max) {
                myBarChart.options.scales.yAxes[0].ticks.max = 2 * max_function_invocation
            }
            myBarChart.data.labels = functions_name
            myBarChart.data.datasets[0].data = functions_invocation


            myBarChart.update()
        })
    }


</script>
</body>

</html>